<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;
use App\Service\Phpredis;


class GameMapServer extends  Model{

    const MAP_CACHE_KEY = "server:map:connect";

   	public function paginate()
    {
    	$perPage = Request::get('per_page', 20);

        $page = Request::get('page', 1);

        $start = ($page-1)*$perPage;

        $redis = Phpredis::Redis("default");
 
                     //获取map连接
        $subjects = $redis->hgetall(self::MAP_CACHE_KEY)?:[];

        $subjects = array_slice($subjects, $start, $perPage);
        foreach ($subjects as &$val) {
            $val = json_decode($val, true);
            $val['id'] = $val['mid'] ?: ($val['mid'] = $val['mapId']);
        }

//        $data = [
//            'count' => $perPage,
//            'subjects' => $subjects,
//            'total' => count($subjects),
//            'start' => $start,
//            'title' => 'map服务列表',
//        ];
//
//var_dump($start, $perPage);
        //$data = $data->toArray();

        // $data = json_decode($data, true);

        //$list = static::hydrate($subjects);

        $paginator = new LengthAwarePaginator($subjects, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }

    public static function with($relations)
    {
        return new static;
    }

    public static function MapSave($id, $data){
        
        $redis = Phpredis::Redis("default");
        
        $src = $redis->hget(self::MAP_CACHE_KEY, $id);
        $src = json_decode($src, true);
        
        $data = array_merge($src?:[], $data);
        $redis->hset(self::MAP_CACHE_KEY, $id, $data);
    }

    public static function findOne($id){
        $redis = Phpredis::Redis("default");
        
        $src = $redis->hget(self::MAP_CACHE_KEY, $id);
        $src = json_decode($src, true);

        !$src['mid'] && $src['mid'] = $src['mapId'];
       
        return $src;
    }

}

